package org.common.utils.generatormapper.event.handler;
import org.common.utils.database.access.DataAccess;
import org.common.utils.database.access.DataAccessTool;
import org.common.utils.event.annotation.EventMethod;
import org.common.utils.generatormapper.GeneratorMapperManager;
import org.common.utils.generatormapper.data.entity.DataEntity;
import org.common.utils.generatormapper.event.entity.CloseEvent;
import org.common.utils.generatormapper.event.entity.SelectDirEvent;
import org.common.utils.generatormapper.event.entity.SelectTableEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import java.awt.*;
import java.io.File;

/**
 * 事件处理
 * @author zhouzhibing
 * @date 2025/2/24
 */
public class CommonEventHandler {
    private Logger log = LoggerFactory.getLogger(CommonEventHandler.class);

    /**
     * 关闭事件
     * @param event
     */
    @EventMethod
    public void close(CloseEvent event) {
        GeneratorMapperManager.getInstance().getDataManager().save();
    }

    /**
     * 选择目标
     * @param event
     */
    @EventMethod
    public void selectDir(SelectDirEvent event) {
        JTextField txtGeneratorPath = event.getTxtGeneratorPath();
        JFrame mainFrame = event.getGeneratorEntityWindow();

        JFileChooser jFileChooser = new JFileChooser();
        jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int result = jFileChooser.showOpenDialog(mainFrame);
        if(result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = jFileChooser.getSelectedFile();

            DataEntity dataEntity = GeneratorMapperManager.getInstance().getDataManager().getDataEntity();
            dataEntity.setJavaDir(selectedFile.getAbsolutePath());
            txtGeneratorPath.setForeground(Color.BLACK);
            txtGeneratorPath.setText(selectedFile.getAbsolutePath());
            log.info("CommonEventHandler selectedFile = {} " , selectedFile.getAbsolutePath());
        }
    }

    /**
     * 选择表
     * @param event
     */
    @EventMethod
    public void selectTable(SelectTableEvent event) {
        ListSelectionEvent eventSource = event.getEventSource();
        if (!eventSource.getValueIsAdjusting()) {
            log.info("CommonEventHandler.selectTable adjusting false");
            return;
        }

        JList<String> jList = (JList<String>)eventSource.getSource();
        String selectedValue = jList.getSelectedValue();

        DataAccess dataAccess = DataAccessTool.get().getDataAccess();
        dataAccess.select("SHOW CREATE table " + selectedValue, resultSet -> {
            String value = resultSet.getString(2);
            System.out.println(value);
            return null;
        });
    }
}
